using UnityEditor;
using UnityEngine;

namespace GameDesigner
{
    [CustomEditor(typeof(AnimationClipReference))]
    public class AnimationClipReferenceEditor : Editor
    {
        private AnimationClipReference animationClipReference;

        private void OnEnable()
        {
            animationClipReference = target as AnimationClipReference;
        }

        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();
            var rect = EditorGUILayout.GetControlRect(GUILayout.Height(100));
            GUI.Box(rect, new GUIContent("将动画剪辑拖入这里!!!"), EditorStyles.selectionRect);
            if (Event.current.type == EventType.DragUpdated || Event.current.type == EventType.DragPerform)
            {
                if (rect.Contains(Event.current.mousePosition))
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                    HandleDragDrop();
                }
            }
        }

        private void HandleDragDrop()
        {
            if (Event.current.type == EventType.DragPerform)
            {
                foreach (var obj in DragAndDrop.objectReferences)
                {
                    if (obj is AnimationClip clip)
                    {
                        if (!animationClipReference.ClipNames.Contains(clip.name))
                            animationClipReference.ClipNames.Add(clip.name);
                    }
                    else
                    {
                        var relativePath = AssetDatabase.GetAssetPath(obj);
                        var modelImporter = AssetImporter.GetAtPath(relativePath) as ModelImporter;
                        if (modelImporter == null)
                            continue;
                        var clipAnimations = modelImporter.clipAnimations;
                        if (clipAnimations.Length == 0)
                            continue;
                        foreach (var clipAnimation in clipAnimations)
                        {
                            if (!animationClipReference.ClipNames.Contains(clipAnimation.name))
                                animationClipReference.ClipNames.Add(clipAnimation.name);
                        }
                    }
                }
            }
        }
    }
}